package org.phpsx.amun.newsreader;

import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JEditorPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 * NewsTable
 * 
 * @author     Christoph Kappestein <k42b3.x@gmail.com>
 * @license    http://www.gnu.org/licenses/gpl.html GPLv3
 * @link       http://amun.phpsx.org
 * @category   example
 * @package    newsreader
 * @version    $Revision: 633 $
 */
public class NewsTable extends JTable
{
	protected TableCellRenderer cellRenderer;

	public NewsTable(NewsModel model, TableColumnModel cm)
	{
		super(model, cm);

		cellRenderer = new NewsRenderer();
	}

	public TableCellRenderer getCellRenderer(int row, int column)
	{
		return cellRenderer;
	}

	class NewsRenderer implements TableCellRenderer
	{
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
		{
			if(value != null)
			{
				try
				{
					NewsModel tm = (NewsModel) getModel();

					// get values
					String title = (String) tm.getValueAt(row, 3);
					String content = (String) tm.getValueAt(row, 4);
					Date date = sdf.parse((String) tm.getValueAt(row, 5));
					String user = (String) tm.getValueAt(row, 6);

					// build editor pane
					String html = "<html><body><h1>" + title + "</h1><p><small>created on: " + sdf.format(date) + " by " + user + "</small></p>" + content + "</body></html>";

					JEditorPane pane = new JEditorPane("text/html", html);
					pane.setSize(table.getSize().width, Integer.MAX_VALUE);
					pane.setEditable(false);

					HTMLEditorKit kit = new HTMLEditorKit();
					pane.setEditorKit(kit);

					StyleSheet styleSheet = kit.getStyleSheet();
					styleSheet.addRule("body {font-family:\"Helvetica Neue\", Arial, Helvetica, sans-serif;}");
					styleSheet.addRule("h1 {margin:2px;padding:2px;}");
					styleSheet.addRule("p {margin:2px;padding:2px;}");

					Document doc = kit.createDefaultDocument();
					pane.setDocument(doc);
					pane.setText(html);

					if(hasFocus)
					{
						/*
						pane.setOpaque(true);
						pane.setBackground(SystemColor.activeCaption);
						pane.setForeground(SystemColor.activeCaptionText);
						*/
					}

					// set height
					if(pane.getPreferredSize().height != table.getRowHeight(row))
					{
						table.setRowHeight(row, pane.getPreferredSize().height);
					}

					return pane;
				}
				catch(Exception e)
				{
				}
			}

			return null;
		}
	}
}
